package com.atguigu.gmall.common.config.minio.service.Impl;

import com.atguigu.gmall.common.config.minio.MinioAutoConfiguration;

import com.atguigu.gmall.common.config.minio.MinioProperties;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.*;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * ClassName: FileUploadServiceImpl
 * Package: com.atguigu.gmall.product.service.impl
 * Description:
 *
 * @Author ltystart
 * @Create 2025/8/21 9:15
 * @Version 1.0
 */
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioAutoConfiguration minioAutoConfiguration;

    @Autowired
    private MinioProperties minioProperties;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @Override
    public String upload(MultipartFile file) throws Exception {
        //文件名唯一
        String filename = UUID.randomUUID().toString().replaceAll("-", "") + "-" + file.getOriginalFilename();
        InputStream fis = file.getInputStream();

        //3.上传文件
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(filename)
                .stream(fis, fis.available(), -1L)
                .build();
        minioAutoConfiguration.minioClient().putObject(putObjectArgs);
        //4、拿到文件的访问路径http://192.168.200.100:9b00/mall/1.png
        String url = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + filename;
        return url;
    }
}
